import { request } from "../../utils/util";

const app = getApp();
Page({
  data: {
    top: app.globalData.rightBarInfo.top,
    height: app.globalData.rightBarInfo.height,
    windowHeight: app.globalData.systemInfo.windowHeight,
    address: []
  },
  toAddress (e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/editAddress/index?id=${id || ''}`
    })
  },
  del(e) {
    wx.showModal({
      title: '提示',
      content: '确定删除该地址吗？',
      success:(res) => {
        if (res.confirm) {
          const { id } = e.currentTarget.dataset;
          this.delAddress(id)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 删除地址
  delAddress(id) {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/consignees/${id}`,
      method: 'DELETE',
      success: ({ code, message }) => {
        wx.hideLoading()
        if (code === 200) {
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
          this.getAddress()
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  setDefault (e) {
    let { item } = e.currentTarget.dataset
    if (item.is_default === 0) {
      return false
    }
    item.is_default = 0
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: `/api/web/consignees/${item.id}`,
      method: 'PUT',
      data: item,
      success: ({ code, message }) => {
        wx.hideLoading()
        if (code === 200) {
          wx.showToast({
            title: '设置成功',
            icon: 'success',
            duration: 2000
          })
          this.getAddress()
        } else {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 选择地址
  chooseAddr(e) {
    if (this.options.type === 'choose') {
      let { item } = e.currentTarget.dataset
      app.globalData.chooseAddress = item
      wx.navigateBack()
    }
  },
  // 获取地址列表
  getAddress() {
    wx.showLoading({
      title: '加载中..',
      mask: true
    })
    request({
      url: '/api/web/consignees',
      success: ({ code, data }) => {
        wx.hideLoading()
        if (code === 200) {
          this.setData({
            address: data
          })
        }
      }
    })
  },
  onShow() {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#000000',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    this.getAddress()
  },
})
